import { ref, onMounted, onUnmounted } from "vue";
import { addBill } from "../../api/modules/bill.api";  // 使用新增账单接口

export function useAddPage() {
    
    const categories = ref([
        { name: "餐饮", icon: "🍕" },
        { name: "交通", icon: "🚆" },
        { name: "购物", icon: "🛒" },
        { name: "生活缴费", icon: "💡" },
    ]);
    const selectedCategory = ref("餐饮");
    const inputValue = ref("");

    // 新增日期和备注字段
    const formatDate = (date: Date): string => {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        return `${year}-${month}-${day}`;
    };
    const selectedDate = ref(formatDate(new Date()));
    const remark = ref("");

    // 新增 loading 和 modal 状态
    const isLoading = ref(false);
    const modalVisible = ref(false);
    const modalTitle = ref("提示");
    const modalMessage = ref("");

    // Snackbar 状态管理
    const snackbarVisible = ref(false);
    const snackbarMessage = ref("");
    const snackbarType = ref<'success' | 'error' | 'info'>('success');

    // 定义键盘布局，新增运算符和小数点按钮
    const keypadRows = ref([
        ["1", "2", "3", "+"],
        ["4", "5", "6", "-"],
        ["7", "8", "9", "."],
        ["0"],
    ]);

    // 账单类型默认符号：默认为 "-" 表示支出，切换后相应修改为 "+"
    const currentOperator = ref("-");

    // 设置运算符（账单类型切换）
    const setOperator = (op: string) => {
        currentOperator.value = op;
        // 切换账单类型后清空金额输入，避免混淆
        inputValue.value = "";
    };

    // 数字和运算符按钮输入
    const appendKey = (key: string) => {
        if (!key) return;
        inputValue.value += key;
    };

    // 删除最后一位
    const deleteLast = () => {
        inputValue.value = inputValue.value.slice(0, -1);
    };

    // 点击完成后：计算表达式并提交数据到后端  
    // 组装数据格式：bill_date、amount（计算结果×账单类型符号）、category、remark
    const onComplete = async () => {
        if (inputValue.value === "") return;
        // 如果表达式末尾为运算符或小数点则提示补全表达式
        if (/[\+\-\.]$/.test(inputValue.value)) {
            alert("请补全计算表达式");
            return;
        }
        let result: number;
        try {
            result = eval(inputValue.value);
        } catch (error) {
            alert("输入错误，请检查算式");
            return;
        }
        // 取计算结果绝对值后，根据当前默认操作符决定正负
        result = Math.abs(result);
        if (currentOperator.value === "-") {
            result = -result;
        }
        inputValue.value = result.toString();

        // 组装提交给后端的数据
        const payload = {
            bill_date: selectedDate.value,
            amount: result,
            category: selectedCategory.value,
            remark: remark.value,
        };

        isLoading.value = true;
        try {
            await addBill(payload);
            // 使用 Snackbar 显示成功提示
            snackbarMessage.value = "账单新增成功！";
            snackbarType.value = "success";
            snackbarVisible.value = true;
            // 清空输入等数据
            inputValue.value = "";
            remark.value = "";
        } catch (error) {
            console.error("提交账单失败", error);
            // 使用 Snackbar 显示错误提示
            snackbarMessage.value = "提交账单失败，请重试";
            snackbarType.value = "error";
            snackbarVisible.value = true;
        } finally {
            isLoading.value = false;
        }
    };

    // 判断是否为手机（宽度小于等于768）
    const isMobile = ref(window.innerWidth <= 768);
    const handleResize = () => {
        isMobile.value = window.innerWidth <= 768;
    };
    onMounted(() => window.addEventListener("resize", handleResize));
    onUnmounted(() => window.removeEventListener("resize", handleResize));

    const closeModal = () => {
        modalVisible.value = false;
    };

    const hideSnackbar = () => {
        snackbarVisible.value = false;
    };

    return {
        categories,
        selectedCategory,
        inputValue,
        keypadRows,
        appendKey,
        deleteLast,
        onComplete,
        isMobile,
        selectedDate,
        remark,
        isLoading,
        modalVisible,
        modalTitle,
        modalMessage,
        closeModal,
        currentOperator,
        setOperator,
        snackbarVisible,
        snackbarMessage,
        snackbarType,
        hideSnackbar,
    };
}